/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.reserveView;
/**
 * 说明：
 * 库存报警
 * @Author：
 * @Date：2012-03-21
 */
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumnModel;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TStockAlarm;
import com.ruipengkj.bean.TStore;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.base.query.PageIndex;
import com.ruipengkj.commons.base.query.PageModel;
import com.ruipengkj.commons.base.query.PageView;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.DataPackageComponent;
import com.ruipengkj.component.JComboBoxPOJO;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.JPanelFlowLayoutComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.RPJButtonGray;
import com.ruipengkj.component.RPJButtonRoundBlue;
import com.ruipengkj.component.RPJButtonRoundOrager;
import com.ruipengkj.component.jpanel.QueryPanel;
import com.ruipengkj.component.page.PageDelegale;
import com.ruipengkj.component.page.PagingComponent;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.ColorTableCellRenderer;
import com.ruipengkj.model.StockAlarmModel;
import com.ruipengkj.service.TStockAlarmService;
import com.ruipengkj.service.TStoreService;
import com.ruipengkj.view.base.BasePagePanel;

public class StockAlarmPanel extends BasePagePanel<TStockAlarm> implements PageDelegale ,Runnable{

private static final long serialVersionUID = 1L;
	
	private JLabelJComboBoxComponent reserveID;//仓库
	
	private DataPackageComponent startTime; //查询   开始时间段
	private DataPackageComponent endTime; //结束时间段
	
	private JButton queryButton;//查询
	private JButton clearButton;//清除按钮
	private JButton addButton; //添加
	private JButton delButton; //删除
	
	private JTable table;
	private JScrollPane tableJsp;
	
	private PagingComponent pagingComponent;//翻页组件
	private PageView<TStockAlarm> pageView;//翻页主键
	
	private TStockAlarmService tStockAlarmService;//库存预警
	
	private StockAlarmModel stockAlarmModel;
	private TStoreService tStoreService;//仓库
	
	public StockAlarmPanel() {
		tStoreService = BuildSpringApplication.getInstance().getTStoreServiceImpl();
		tStockAlarmService = BuildSpringApplication.getInstance().getTStockAlarmServiceImpl();
		this.setLayout(new BorderLayout());
		this.init();
		this.initListener();
	}
	
	private List<TStore> selectStore(TStore entity) {
		List<TStore> tStoreList = null;
		try {
			tStoreList = tStoreService.findService(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tStoreList;
	}
	
	private JPanel initTop() {
		QueryPanel queryPanel=new QueryPanel("库存报警",ImageFactory.loadImage(ImageFactory.FUN_5_ICON_5));
		JPanel top_panel =uiFactory.createGridJPanel(2, 1);
		reserveID = new JLabelJComboBoxComponent("仓库名称：", new String[]{}, 188);
		SwingUtilities.invokeLater(queryStore);
		startTime = new DataPackageComponent("开始时间：", 15);
		endTime = new DataPackageComponent("结束时间：", 15);
		queryButton = new RPJButtonBlue("查询");
		clearButton=new RPJButtonGray("清空");
		JPanel jp1 = new JPanelFlowLayoutComponent(new Component[]{reserveID, startTime, endTime, queryButton, clearButton
		}, FlowLayout.LEFT);
		top_panel.add(jp1);
		top_panel.add(new JLabel("  白色：表示没有达到最低伐值/最高伐值。" +
				"红色：表示指定仓库的指定商品达到最高阀值。绿色：表示指定仓库的指定商品达到最低阀值。"));
		queryPanel.addPanel(top_panel);
//		queryPanel.addBorderPanel(top_panel);
		return queryPanel;
	}
	
	private JPanel initTail() {
		
		JPanel tail_panel = uiFactory.createGridJPanel(1, 2);

		addButton = new RPJButtonRoundBlue("添加(Ctrl+A)");
		delButton = new RPJButtonRoundOrager("删除(Ctrl+D)");
		JPanel jp1 = new JPanelFlowLayoutComponent(new Component[]{addButton, delButton}, FlowLayout.LEFT);
		pagingComponent=new PagingComponent();
		pagingComponent.setPageDelegale(this);
		pageView = new PageView<TStockAlarm>();
		tail_panel.add(jp1);
		tail_panel.add(pagingComponent);
		return tail_panel;
	}
	
	private void init() {
		stockAlarmModel = new StockAlarmModel();
		table=uiFactory.createRPJTable(stockAlarmModel, null, this, 30, JLabel.CENTER);
		
		tableJsp=uiFactory.createJScrollPane(table);
		add(initTop(), BorderLayout.NORTH);
		add(tableJsp, BorderLayout.CENTER);
		add(initTail(), BorderLayout.SOUTH);
	}
	
	private void initListener() {
		clearButton.addActionListener(this);
		queryButton.addActionListener(this);
		addButton.addActionListener(this);
		delButton.addActionListener(this);
		addButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		delButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_D, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == queryButton) {
			this.termQuery(1);
		} else if(e.getSource() == addButton) {
			StockAlarmAddDialog stockAlarmAddDialog = new StockAlarmAddDialog(null, "添加库存报警", true);
			stockAlarmAddDialog.showDialog(null);
			if(stockAlarmAddDialog.isSuccess){
				this.termQuery(1);
			}
		} else if(e.getSource() == delButton) {
			if (table.getSelectedRow() < 0 || table.getSelectedRow() > table.getRowCount()) {
				JOptionPane.showMessageDialog(null, "请选择删除的表！");
				return;
			}
			if(Util.showConfirmDialog("是否删除此表？")==0){
				try {
					tStockAlarmService.deleteService((String)table.getValueAt(table.getSelectedRow(), 0));
					JOptionPane.showMessageDialog(null, "删除成功！");
				} catch (Exception e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, "删除失败！");
				}
				this.termQuery(1);
			}
		} else if (e.getSource() == clearButton) {
			reserveID.getBox().setSelectedIndex(0);//仓库
			startTime.setDate(null); //查询   开始时间段
			endTime.setDate(null); //结束时间段
		}
	}
	
	public void mouseClicked(MouseEvent e) {
		if (e.getSource() == table && e.getClickCount() == 2) {
			String alarmID = (String)table.getValueAt(table.getSelectedRow(), 0);
			try {
				TStockAlarm tStockAlarm = tStockAlarmService.getByIdService(alarmID);
				StockAlarmAddDialog stockAlarmAddDialog = new StockAlarmAddDialog(null, "库存报警修改", true);
				stockAlarmAddDialog.showDialog(tStockAlarm);
				if(stockAlarmAddDialog.isSuccess){
					this.termQuery(1);
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
	
	@Override
	public void run() {
		this.termQuery(1);
	}
	
	//比较是否达到最低阀值 或 最高阀值
	private void compare(List<TStockAlarm> tStockAlarmList) {
		if(tStockAlarmList != null) {
			List<Integer> redList = new ArrayList<Integer>();
			List<Integer> greedList = new ArrayList<Integer>();
			for(int i = 0; i < tStockAlarmList.size(); ++i) {
				TStockAlarm tStockAlarm = tStockAlarmList.get(i);
				int num = 0;//num当前库存量
				if (tStockAlarm.getType().equals("2.任一仓库报警")) {
					for (int j = reserveID.getModel().getSize() - 1; j >= 0; --j) {
//						num = ApplicationContext
						return;
					}
				} else {
					if (tStockAlarm.getType().equals("1.总量报警")) {
						num = ApplicationContext.stockTotalNum(tStockAlarm.getTCommodity().getCommodityID(), null);
					} else {//if (tStockAlarmList.get(i).getType().equals("3.某一仓库报警"))
						//num当前库存量
						num = ApplicationContext.stockTotalNum(tStockAlarm.getTCommodity().getCommodityID(), tStockAlarm.getStoreID());
					}
				
					tStockAlarmList.get(i).setNum(num);//显示在table中的库存总量
					if (num >= tStockAlarmList.get(i).getMaxWalve()) {
						redList.add(i);//当当前库存量大于等于最高阀值时，放入红色List
					} 
					if (num <= tStockAlarmList.get(i).getMinWalve()) {
						greedList.add(i);//当当前库存量小于等于最低阀值时，放入绿色List
					}
				}
			}
			
			//设置table颜色
			TableColumnModel columnModel = table.getColumnModel();
			for (int i = table.getColumnCount() - 1; i >= 0; --i) {
				columnModel.getColumn(i).setCellRenderer(new ColorTableCellRenderer(redList, greedList));
			}
		}
	}
	
	//读取仓库数据
	private Runnable queryStore=new Runnable() {
		@Override
		public void run() {
			try {
				reserveID.addElement(new JComboBoxPOJO("所有仓库……"));
				List<TStore> tStoreList = tStoreService.findService(null);
				if (tStoreList != null && tStoreList.size()!=0) {
					int length = tStoreList.size();
					for(int i = 0; i < length; ++i) {
						TStore tStore=tStoreList.get(i);
						reserveID.addElement(new JComboBoxPOJO(tStore.getStoreID(),tStore.getName(),tStore));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	//条件查询
	@Override
	protected void termQuery(final int currentPage){
		final TStockAlarm tStockAlarm = new TStockAlarm();
		
//		tStockAlarm.setStoreID(reserveID.getBox().getSelectedItem().toString());
		if (reserveID.getBox().getSelectedIndex() != 0) {
			JComboBoxPOJO po = (JComboBoxPOJO)reserveID.getBox().getSelectedItem();
			if (po != null && po.getObject() != null) {
				tStockAlarm.setStoreID(((TStore)po.getObject()).getStoreID());
			}
		} else {
			tStockAlarm.setStoreID(null);
		}
		
		tStockAlarm.setHappenTime(startTime.getDate());
		tStockAlarm.setEndTime(endTime.getDate());
		new Thread(){
			public void run(){
				tableJsp.getViewport().remove(table);
				tableJsp.getViewport().add(waitComponent);
				try {
					pageView.setCurrentPage(currentPage);
					PageModel<TStockAlarm> pageModel = tStockAlarmService.getScrollService(pageView.getFirstResult(), pageView.getMaxResult(),tStockAlarm);
					pageView.setPageModel(pageModel);
					pageView.setPageIndex(PageIndex.getPageIndex(pageView.getPageCode(), pageView.getCurrentPage(), pageView.getTotalPage()));
					if(pageModel!=null){
						final List<TStockAlarm>  list=pageModel.getResultList();
						SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
								compare(list);
								stockAlarmModel.setRowData(list);
								tableJsp.getViewport().remove(waitComponent);
								tableJsp.getViewport().add(table);
								TabelUtil.setJTabelAutoClumnWidth(table);
								pagingComponent.show();
							}
						});
					}else{
						//没有订单数据
						tableJsp.getViewport().remove(waitComponent);
						tableJsp.getViewport().add(table);
						stockAlarmModel.clear();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	@Override
	protected PageView<TStockAlarm> getPageView() {
		return pageView;
	}

	@Override
	public void clear() {
		stockAlarmModel.clear();
		reserveID.getBox().setSelectedIndex(0);//仓库
		startTime.setDate(null); //查询   开始时间段
		endTime.setDate(null); //结束时间段
	}
}